package net.tmaize.dao.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import net.tmaize.dao.BeforeDao;
import net.tmaize.entity.List_news;
import net.tmaize.entity.News_before;
import net.tmaize.utils.ApiUtils;
import net.tmaize.utils.JsonUtils;
import net.tmaize.utils.UrlUtils;

public class BeforeDaoImpl implements BeforeDao {

	private String jsonStr = null;

	@Override
	public News_before getBefore(String date) throws JSONException, IOException {

		jsonStr = JsonUtils.getJsonStr(UrlUtils.beforeUrlChange(ApiUtils.beforeURL + date));
		News_before before = new News_before();
		List<List_news> news = new ArrayList<List_news>();

		JSONTokener jsonTokener = new JSONTokener(jsonStr);
		JSONObject jsonObject = new JSONObject(jsonTokener);
		before.setDate(jsonObject.getString("date"));
		before.setDisplay_date(jsonObject.getString("display_date"));

		JSONArray jsonArray = jsonObject.getJSONArray("news");

		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jb = jsonArray.getJSONObject(i);
			String title = jb.getString("title");
			String url = jb.getString("url");
			String image = jb.getString("image");
			String share_url = jb.getString("share_url");
			String thumbnail = jb.getString("thumbnail");
			String ga_prefix = jb.getString("ga_prefix");
			String id = jb.getString("id");
			news.add(new List_news(title, url, UrlUtils.imageUrlChange_1(image), share_url,UrlUtils.imageUrlChange_1(thumbnail), ga_prefix, id));
		}
		before.setNews(news);
		return before;
	}

	@Override
	public String getJsonStr() {
		return jsonStr;
	}

}
